package com.loadagent.core;

import java.lang.instrument.*;
import java.util.*;
import java.security.*;

import com.loadagent.core.util.*;

import java.io.*;

public class AgentTransformer implements ClassFileTransformer {
    private HashMap<String, char[]> pwds;

    public AgentTransformer() {
        this.pwds = new HashMap<String, char[]>();
    }

    @Override
    public byte[] transform(final ClassLoader loader, String className, final Class<?> classBeingRedefined, final ProtectionDomain domain, final byte[] classBuffer) {
        if (className == null || domain == null || loader == null) {
            return classBuffer;
        }
        String projectPath = domain.getCodeSource().getLocation().getPath();
        projectPath = JarUtils.getRootPath(projectPath);
        if (StrUtils.isEmpty(projectPath)) {
            return classBuffer;
        }
        className = className.replace("/", ".").replace("\\", ".");
        if (!className.startsWith("com.ysy.tz")) {
            return classBuffer;
        }
        char[] pwd = this.pwds.get(projectPath);
        if (pwd == null) {
            pwd = this.findPwd(projectPath);
        }
        //解密
        final byte[] bytes = JarDecryptor.getInstance().doDecrypt(projectPath, className, pwd);
        if (bytes != null && bytes[0] == -54 && bytes[1] == -2 && bytes[2] == -70 && bytes[3] == -66) {
            return bytes;
        }
        return classBuffer;
    }

    public char[] findPwd(final String rootPath) {
        final char[] pwd = JarDecryptor.readPassFromJar(new File(rootPath));
        this.pwds.put(rootPath, pwd);
        return pwd;
    }
}
